import { getOrientation } from './exif'

export const getBase64 = async (file, options = {}) => {
	if (typeof file !== 'object') {
		return {}
	}
	const option = {
		limitW: 750,
		limitH: 1334,
		...options
	}

	const Orientation = await getOrientation(file)
	return new Promise((resolve, reject) => {
		var reader = new FileReader()
		reader.onload = function (e) {
			var data = e.target.result
			var image = new Image()
			image.onload = function() {
				let imgWidth = this.width
				let imgHeight = this.height
				// 控制上传图片的宽高
				if (imgWidth > imgHeight && imgWidth > option.limitW) {
					imgWidth = option.limitW
					imgHeight = Math.ceil(option.limitW * this.height / this.width)
				} else if (imgWidth < imgHeight && imgHeight > option.limitH) {
					imgWidth = Math.ceil(option.limitH * this.width / this.height)
					imgHeight = option.limitH
				}

				const canvas = document.createElement('canvas')
				const ctx = canvas.getContext('2d')
				canvas.width = imgWidth
				canvas.height = imgHeight
				if (Orientation && Orientation !== 1) {
					switch (Orientation) {
						case 6: // 旋转90度
							canvas.width = imgHeight
							canvas.height = imgWidth
							ctx.rotate(Math.PI / 2)
							ctx.drawImage(this, 0, -imgHeight, imgWidth, imgHeight)
							break
						case 3: // 旋转180度
							ctx.rotate(Math.PI)
							ctx.drawImage(this, -imgWidth, -imgHeight, imgWidth, imgHeight)
							break
						case 8: // 旋转-90度
							canvas.width = imgHeight
							canvas.height = imgWidth
							ctx.rotate(3 * Math.PI / 2)
							ctx.drawImage(this, -imgWidth, 0, imgWidth, imgHeight)
							break
					}
				} else {
					ctx.drawImage(this, 0, 0, imgWidth, imgHeight)
				}
				let dataURL = canvas.toDataURL(file.type, option.ratio || 1)
				// dataURL = dataURL.replace(`data:${file.type};base64,`, '') // 去掉前缀，上传接口接受数据不支持前缀
				resolve(dataURL)
			}
			image.src = data
		}
		reader.readAsDataURL(file)
	})
}
